package com.kind.perm.wx.common.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.kind.common.uitls.WxUtils;
import com.kind.perm.core.account.domain.AccountDO;
import com.kind.perm.core.account.service.AccountService;
import com.kind.perm.wx.common.ResourceUtil;

import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

/**
 * 
 * Function:日志拦截器. <br/>
 * 
 * @date:2016年5月12日 上午11:16:33 <br/>
 * @author 李明
 * @version:
 * @since:JDK 1.7
 */
public class WxInterceptor implements HandlerInterceptor {

	@Autowired
	AccountService accountService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//测试注释 上线前放开
//		String code = request.getParameter("code");
//		User wxUser=null;
//		if(code==null||"".equals(code)){
//
//			String query = "";
//		     if(request.getQueryString()!=null && !"".equals(request.getQueryString())){
//		    	 query = "?" + request.getQueryString();
//		     }
//		     String url = (request.getRequestURL() + query).toString();
//			
//		     String fullurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ResourceUtil.WX_appid+"&redirect_uri="+URLEncoder.encode(url,"UTF-8")+"&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect";
//			response.sendRedirect(fullurl);
//			return false;
//		}else{
//			SnsToken token = SnsAPI.oauth2AccessToken(ResourceUtil.WX_appid, ResourceUtil.WX_appsecret, code);
//			wxUser = SnsAPI.userinfo(token.getAccess_token(), token.getOpenid(), "zh_CN");
//		}
		
		//测试放开 上线前注释
		User wxUser = new User();
		wxUser.setOpenid("oyqTtw1TyV2TRmTIVeF1Z3R3wqaw");
		wxUser.setNickname("胡哥");
		wxUser.setSex(0);
		wxUser.setHeadimgurl("http://wx.qlogo.cn/mmopen/iahdQicCC5VBSCGg65m04jn1yvHVIibexDJjcVXqicSmmWpyOuxw5Xiahuyia6c6icScfsDBv5PI6iaEBm3t9mmXKUHYMibHyUstBRgaib/0");
		
		AccountDO account = new AccountDO();
		account.setOpenId(wxUser.getOpenid());
		account.setName(wxUser.getNickname());
		account.setSex(wxUser.getSex().toString());
		account.setHeadImage(wxUser.getHeadimgurl());
		account.setLastLoginIp(request.getRemoteAddr());
		
		account = accountService.saveOrUpdateByOpenId(account);
		
		request.getSession().setAttribute(WxUtils.WX_session_account,account);
		
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
